﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;


namespace General.Mvc.Filters
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _env;

        private readonly Serilog.ILogger logger;

        public GlobalExceptionFilter(IWebHostEnvironment env, Serilog.ILogger logger)
        {
            _env = env;
           

            this.logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            Exception exception = context.Exception;
            string error = string.Empty;

            error += string.Format("{0} | {1} ", exception.StackTrace, exception.InnerException);

            var json = new { message = exception.Message, detail = error, code = 0 };
            if (_env.IsDevelopment())
            {
                context.Result = new InternalServerErrorObjectResult(json);
            }
            else
            {
                //写入日志
                logger.Error(JsonHelper.Serialize(json));
                context.Result = new RedirectResult("/Main/Index");
            }

        }
    }

    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object error) : base(error)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }
}
